package com.jxpanda.infrastructure.crypto.algorithm.encrypt.contract;

import javax.crypto.Cipher;
import javax.crypto.NoSuchPaddingException;
import javax.crypto.SecretKey;
import javax.crypto.spec.IvParameterSpec;
import java.security.InvalidAlgorithmParameterException;
import java.security.InvalidKeyException;
import java.security.NoSuchAlgorithmException;

/**
 * 对称加密算法
 */
public interface SymmetricEncrypt extends Encrypt<SecretKey> {

    IvParameterSpec getIv();

    @Override
    default Cipher createCipher(int mode) {
        try {
            Cipher cipher = Cipher.getInstance(getAlgorithm());
            if (getIv() == null) {
                cipher.init(mode, getKey());
            } else {
                cipher.init(mode, getKey(), getIv());
            }
            return cipher;
        } catch (NoSuchAlgorithmException | NoSuchPaddingException | InvalidKeyException |
                 InvalidAlgorithmParameterException e) {
            throw new RuntimeException(e);
        }

    }
}
